package com.alnex.drools.controller;

import com.alnex.drools.model.fact.AddressCheckResult;
import com.alnex.drools.model.filter.MyAgendaFilter;
import com.alnex.drools.pojo.Address;
import com.alnex.drools.utils.KieUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.AgendaFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("address")
@Slf4j
public class AddressController {

    @GetMapping("/{postCode}")
    public Object address(@PathVariable("postCode") String postCode) {
        KieSession kieSession = KieUtils.getKieSession();

        Address address = new Address();
        address.setPostcode(postCode);

        AddressCheckResult result = new AddressCheckResult();
        kieSession.insert(address);
        kieSession.insert(result);

        kieSession.getAgenda().getAgendaGroup("address").setFocus();
        int ruleFiredCount = kieSession.fireAllRules();
        System.out.println("触发了" + ruleFiredCount + "条规则");

        if (result.isPostCodeResult()) {
            return "address / 执行结束   规则校验通过";
        }
        return "address / 执行结束   规则校验未通过";
    }

    @GetMapping("/address-test/{num}")
    public Object addressTest(@PathVariable("num") Integer num) {
        Address address = new Address();
        address.setPostcode(generateRandom(num));

        KieServices kieServices = KieUtils.getKieServices();
        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        KieSession kieSession = kieContainer.newKieSession("addressTest");

        // 选择agenda-group
        kieSession.getAgenda().getAgendaGroup("addressTest").setFocus();
        // 增加自定义AgendaFilter
        AgendaFilter agendaFilter = new MyAgendaFilter("[AddressTest]");

        AddressCheckResult addressCheckResult = new AddressCheckResult();
        kieSession.insert(address);
        kieSession.insert(addressCheckResult);

        int ruleFiredCount = kieSession.fireAllRules(agendaFilter);
        kieSession.dispose();
        System.out.println("触发了" + ruleFiredCount + "条规则");

        if (addressCheckResult.isPostCodeResult()) {
            return "address / 执行结束   规则校验通过";
        }
        return "address / 执行结束   规则校验未通过";
    }

    /**
     * 生成随机数
     *
     * @param num
     * @return
     */
    public String generateRandom(Integer num) {
        String chars = "0123456789";
        StringBuffer number = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int rand = (int) (Math.random() * 10);
            number = number.append(chars.charAt(rand));
        }
        return number.toString();
    }
}
